﻿using Autofac;
using SlamCms.SharePoint.UserManagement;
using SlamCms.Common;
using System.Data.SqlClient;
using SlamCms.Data;
using System.Data;
using System.Data.Common;
using SlamCms.Data.Repositories;
using System;
using Slam.Configuration;
using Slam;
using Slam.SharePoint;
using SlamCms.SharePoint.Core;
using System.Linq;
using Microsoft.SharePoint;
using SlamCms.Configuration;
using SlamCms.Web;
using SlamCms.SharePoint.Services;
using Autofac.Integration.Web;
using SlamCms.DomainEvents;

namespace SlamCms.SharePoint
{
	public class SlamCmsSharePointBootstrapper : Bootstrapper
	{
		public override void PreApplicationStart(PreApplicationStartContext context)
		{	
			RegisterDependecies(context);
		}

		public override void PostApplicationStart(PostApplicationStartContext context)
		{
			if (context.Application is IContainerProviderAccessor)
			{
				((SlamCmsApplication)context.Application).ContainerProvider = new ContainerProvider(context.Container);
			}
			SlamCmsConfiguration.Instance.DependencyResolver = new AutofacSlamCmsSharePointDependencyResolver(context.Container);
		}
		
		protected void RegisterDependecies(PreApplicationStartContext context)
		{
			var builder = context.ContainerBuilder;
			builder.RegisterType<CookieManager>();

			// database connection resolver
			builder.RegisterType<DefaultDbConnectionResolver>().As<IDbConnectionResolver>();
			builder.Register(c => c.Resolve<IDbConnectionResolver>().GetConnection()).As<IDbConnection>().InstancePerHttpRequest();

			// register configuration
			builder.Register(c => SlamCmsConfiguration.Instance).SingleInstance();

			// data context
			builder.RegisterType<DataContext>().InstancePerHttpRequest();


			// default registrations
			builder.RegisterType<TrackingRepository>().As<ITrackingRepository>();
			builder.RegisterType<ContentItemRepository>().As<IContentItemRepository>();
		}
	}
}